﻿// 对Date的扩展，将 Date 转化为指定格式的String
// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符，
// 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
// 例子：
// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
// (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18
Date.prototype.Format = function (fmt) { //author: meizz
    var o = {
        "M+": this.getMonth() + 1,                 //月份
        "d+": this.getDate(),                    //日
        "h+": this.getHours(),                   //小时
        "m+": this.getMinutes(),                 //分
        "s+": this.getSeconds(),                 //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds()             //毫秒
    };
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}
//获取浏览器参数
function getQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]);
    return null;
}
//键控的按下事件
var index = 0;
var number = 1;
$(function () {

    $('#l_staff').html($.cookie('realName'));
    $('#l_number').html($.cookie('sysnumber'));
    $('#l_store').html($.cookie('storeName'));

    $('#network_status').html('连通');

    $('#sku').focus(); //当前页面输入框选中
    displayDateTime();

    function displayDateTime() {
        $('#local_time').html((new Date()).Format("yyyy-MM-dd hh:mm:ss"));
        setTimeout(arguments.callee, 1000);
    }

    //主页面快捷键
    $(document).on('keydown', function (e) {
        switch (e.keyCode) {
            case 38: //e.keyCode == 38 上，控制tr的焦点位置
                if (index >= 1) {
                    index--;
                }
                selectRow();
                break;

            case 40: //e.keyCode == 40 下，控制tr的焦点位置
                if (index < $('#ice tr').length - 1) {
                    index++;
                }
                selectRow();
                break;

            case 37: //左,数量减
                var num = $('#list_xz td').eq(3).text();
                var str = '/';
                var str_before = parseInt(num.split(str)[0]); //当前退货数
                var str_after = parseInt(num.split(str)[1]);  //可退货总数
                if (str_before > 0) {
                    str_before = str_before - 1;
                    calNum(str_before, str_after, 1);
                }
                break;

            case 39: //右,数量加
                var num = $('#list_xz td').eq(3).text();
                var str = '/';
                var str_before = parseInt(num.split(str)[0]); //当前退货数
                var str_after = parseInt(num.split(str)[1]);  //可退货总数
                if (str_before < str_after) {
                    str_before = str_before + 1;
                    calNum(str_before, str_after, 2);
                }
                break;

            case 27: //ESC键
                e.preventDefault();  //清除原始快捷
                $.cookie('uid', null);
                $.cookie('phone', null);
                $.cookie('money', null);
                $.cookie('number', null);
                var id = getQueryString("id");
                var sysname = decodeURI(decodeURI(getQueryString("name")));
                sysname = encodeURI(encodeURI(sysname));
                parent.window.location.href = "index.html?id=" + id + "&name=" + sysname;
                break;

            case 13: //回车键
                e.preventDefault();
                var sku = $('#sku').val();
                if (sku != "") {
                    returncolumn(sku);
                    $('#sku').val('');
                } else {
                    //取到总数量
                    var je = $(".bill_money_d").text();
                    var sl = $("#sl").text();
                    var userid = $("#userid").html();
                    var money = $("#money").html();
                    money = money.substring(3, money.length - 3);

                    var id = "", sl = "";

                    var tableId = document.getElementById("ice");
                    for (var i = 0; i < tableId.rows.length; i++) {
                        var linegauge = tableId.rows[i].cells[7].innerHTML;
                        var num = tableId.rows[i].cells[3].innerHTML;
                        var str = '/';
                        var str_before = parseInt(num.split(str)[0]); //当前退货数

                        if (str_before > 0) {
                            id += linegauge + ",";
                            sl += str_before + ",";
                        }
                    }

                    id = id.substring(0, id.length - 1);
                    sl = sl.substring(0, sl.length - 1);
                    $.cookie('tttid', id);
                    $.cookie('tttsl', sl);

                    if (je != 0 && sl != 0) {
                        payment('tsettlement.html?t=1&sl=' + sl + "&je=" + je + "&id=" + userid + "&m=" + money, '600px', '460px');
                    }
                }

                break;
        }
    });
});

/*
 通过上下键选择table下tr的选中
 */
function selectRow() {
    $('#ice tr').attr("id", "");
    $('#ice tr').eq(index).attr("id", "list_xz");

    $('#sku').blur();
    $('#list_xz').focus();
    $('#ice tr').attr("tabindex", "-1");
    $('#sku').focus();
}


//计算并赋值
function calNum(n, mNum, type) {
    var commodityAmount = $('#list_xz td').eq(4).text(); //金额（单商品金额总计）
    //提取金额（单价）
    commodityAmount = parseFloat(commodityAmount.substring(1, commodityAmount.length));
    //单个商品的总价
    var lumpSum = commodityAmount * n;
    //税费
    var taxrate = parseFloat($('#list_xz td').eq(5).text());
    //小计
    var subtotal = lumpSum - taxrate;
    $('#list_xz td').eq(3).text(n + '/' + mNum);
    // $('#list_xz td').eq(4).text('￥' + numFloat(lumpSum));
    $('#list_xz td').eq(6).text('￥' + numFloat(subtotal));

    var totalquantity = parseInt(0);
    var total = parseFloat(0); //总计金额
    var tableId = document.getElementById("ice");
    for (var i = 0; i < tableId.rows.length; i++) {
        var linegauge = tableId.rows[i].cells[6].innerHTML;
        var quantity = parseInt(tableId.rows[i].cells[3].innerHTML);
        if (linegauge != "") {
            linegauge = parseFloat(linegauge.substring(1, linegauge.length));
            total = total + linegauge;
            totalquantity = totalquantity + quantity;
        }
    }

    //得到折让
    var discount = parseFloat($('#zr').text());
    if (type == 2) {
        total = total - discount;
    }
    var receivable = numFloat(total);
    $('.bill_money_d').text(receivable);
    $('#sl').text(totalquantity);
}

//制保留2位小数，如：2，会在2后面补上00.即2.00  
function numFloat(x) {
    var f = parseFloat(x);
    if (isNaN(f)) {
        return false;
    }
    var f = Math.round(x * 100) / 100;
    var s = f.toString();
    var rs = s.indexOf('.');
    if (rs < 0) {
        rs = s.length;
        s += '.';
    }
    while (s.length <= rs + 2) {
        s += '0';
    }
    return s;
}